package org.example.status;

import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import org.example.entity.WaterSensor;
import org.example.sink.WaterSensorMapFunction;

import java.time.Duration;

/**
 * 计算每种传感器的水位和
 */
public class ReduceFunctionDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);


        SingleOutputStreamOperator<WaterSensor> sensorDS = env
                .socketTextStream("hadoop102", 7777)
                .map(new WaterSensorMapFunction())
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((element, ts) -> element.getTs() * 1000L)
                );

        sensorDS.keyBy(r -> r.getId())
                .process(new KeyedProcessFunction<String,WaterSensor,Integer>() {
            private ReducingState<Integer> sumVcState;
            @Override
            public void open(Configuration parameters) throws Exception {
                sumVcState = this
                        .getRuntimeContext()
                        .getReducingState(new ReducingStateDescriptor<Integer>("sumVcState",Integer::sum,Integer.class));
            }

            @Override
            public void processElement(WaterSensor value, Context ctx, Collector<Integer> out) throws Exception {
                sumVcState.add(value.getVc());
                out.collect(sumVcState.get());
            }
        }).print();

        env.execute();
    }
}
